package com.woman.beautylive.presentation.ui.login.splash;

import android.text.TextUtils;

import com.woman.beautylive.data.bean.BaseResponse;
import com.woman.beautylive.data.bean.LoginInfo;
import com.woman.beautylive.data.sharedpreference.PrefsHelper;
import com.woman.beautylive.domain.LocalDataManager;
import com.woman.beautylive.domain.LoginManager;
import com.woman.beautylive.presentation.ui.base.BaseObserver;
import com.woman.beautylive.presentation.ui.base.BasePresenter;
import com.woman.beautylive.presentation.ui.login.LoginSelectActivity;
import com.woman.beautylive.util.L;

import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author Muyangmin
 * @since 1.0.0
 */
public class SplashPresenter extends BasePresenter<SplashUiInterface> {

    private LoginManager loginManager;

    public SplashPresenter(SplashUiInterface uiInterface) {
        super(uiInterface);
        loginManager = new LoginManager();
    }

    public void autoLogin() {
        LoginInfo info = LocalDataManager.getInstance().getLoginInfo();
        if (info == null || TextUtils.isEmpty(info.getToken())) {
            L.w("SplashPresenter", "Attempt auto login but login token is null! info=%s", info);
            return ;
        }
        Subscription subscription = loginManager.autoLogin(info.getToken())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponse<LoginInfo>>(getUiInterface()) {
                    @Override
                    public void onSuccess(BaseResponse<LoginInfo> response) {
                        //update data, e.g. token, balance, etc
                        LocalDataManager.getInstance().saveLoginInfo(response.getData());
                        getUiInterface().startMainActivity();
                    }

                    @Override
                    protected void onDataFailure(BaseResponse<LoginInfo> response) {
                        //静默请求
//                        super.onDataFailure(response);
                        L.w(LOG_TAG, "auto login failure!");
                        getUiInterface().startLoginSelectActivity();
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        //静默请求
//                        super.onError(throwable);
                        getUiInterface().startLoginSelectActivity();
                    }
                });
        addSubscription(subscription);
    }

    public void performFirstStartNavigation(SplashActivity activity) {
        PrefsHelper.setIsFirstRun(false);
        activity.startActivity(LoginSelectActivity.createIntent(activity));
        activity.finish();
    }

    public boolean isFirstRun() {
        return PrefsHelper.getIsFirstRun();
    }

}
